package cn.edu.zufe.mjt.netty;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * @author SKYmada
 * @version 1.0
 */
public class NettyClient {
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new LineBasedFrameDecoder(1024))
                                .addLast(new StringDecoder(StandardCharsets.UTF_8))
                                .addLast(new StringEncoder(StandardCharsets.UTF_8))
                                .addLast(new SimpleChannelInboundHandler<String>() {
                                    @Override
                                    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
                                        System.out.println("客户端收到消息：" + s);
                                    }
                                });
                    }
                });

        ChannelFuture connect = bootstrap.connect("localhost", 8080);
        connect.addListener(f -> {
            if (f.isSuccess()) {
                System.out.println("连接8080成功");
                EventLoop eventLoop = connect.channel().eventLoop();
                eventLoop.scheduleAtFixedRate(() -> {
                    connect.channel().writeAndFlush("你好服务器8080" + System.currentTimeMillis() + "\n");
                }, 0L, 1, TimeUnit.SECONDS);
            } else {
                System.out.println("连接8080失败");
            }
        });
    }
}
